package cn.example.sharedpreferencestest;

import androidx.appcompat.app.AppCompatActivity;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button save = findViewById(R.id.save);
        Button display = findViewById(R.id.display);
        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences.Editor editor = getSharedPreferences("data", MODE_PRIVATE).edit();
                editor.putBoolean("success", true);
                editor.putString("key", "value");
                editor.putInt("number", 100);
                editor.apply();
            }
        });
        display.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences sp = getSharedPreferences("data", MODE_PRIVATE);
                boolean success = sp.getBoolean("success", false);
                String key = sp.getString("key", "");
                int number = sp.getInt("number", 0);
                String result = "success: " + success + ", key: " + key + ", number: " + number;
                Toast.makeText(v.getContext(), result, Toast.LENGTH_SHORT).show();
            }
        });
    }
}